'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, use } from 'react';
import { useSession } from 'next-auth/react';
import { Spinner } from '@/components/ui/Spinner';
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Card, CardContent } from "@/components/ui/card"
import Image from 'next/image';
import CreatableSelect from 'react-select/creatable';
import { motion } from "framer-motion";
import { Loader2, Wand2, HelpCircle } from "lucide-react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalTitle,
} from "@/components/ui/modal"
import { useLanguage } from '@/contexts/LanguageContext';
import { useToast } from "@/hooks/use-toast";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

export default function EditPrompt({ params }) {
  const router = useRouter();
  const { id } = use(params);
  const { language, t } = useLanguage();
  const { toast } = useToast();
  const { data: session } = useSession();
  const [prompt, setPrompt] = useState(() => {
    if (typeof window !== 'undefined') {
      const state = window.history.state;
      if (state?.usr?.state?.prompt) {
        return state.usr.state.prompt;
      }
    }
    return null;
  });
  const [originalVersion, setOriginalVersion] = useState(null);
  const [allVersions, setAllVersions] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [tagOptions, setTagOptions] = useState([]);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [showOptimizeModal, setShowOptimizeModal] = useState(false);
  const [showModelConfig, setShowModelConfig] = useState(false);
  const [modelConfig, setModelConfig] = useState({
    id: null,
    channel: '',
    channel_id: null,
    model: '',
    temperature: 1.0,
    max_tokens: 2048,
    top_p: 1.0,
    presence_penalty: 0.0,
    frequency_penalty: 0.0,
    n: 1,
    stop: '',
    logit_bias: '',
    stream: true,
    api_key: ''
  });

  const [channels, setChannels] = useState([]);
  const [models, setModels] = useState([]);

  useEffect(() => {
    if (id && !prompt) {
      // 获取当前提示词信息
      fetch(`/api/prompts/${id}`)
        .then((response) => response.json())
        .then((data) => {
          setPrompt(data);
          setOriginalVersion(data.version);
          if (data.model_id) {
            fetch(`/api/models/${data.model_id}`)
              .then(res => res.json())
              .then(m => {
                setModelConfig({
                  id: m.id,
                  channel: m.channel || '',
                  channel_id: m.channel_id || null,
                  model: m.model || '',
                  temperature: m.temperature ?? 1.0,
                  max_tokens: m.max_tokens ?? 2048,
                  top_p: m.top_p ?? 1.0,
                  presence_penalty: m.presence_penalty ?? 0.0,
                  frequency_penalty: m.frequency_penalty ?? 0.0,
                  n: m.n ?? 1,
                  stop: (m.stop && Array.isArray(m.stop)) ? m.stop.join(',') : '',
                  logit_bias: m.logit_bias ? JSON.stringify(m.logit_bias) : '',
                  stream: !!m.stream,
                  api_key: m.api_key || ''
                })
              })
              .catch(() => {})
          }
        })
        .catch((error) => console.error('Error fetching prompt:', error));
    } else if (prompt && originalVersion === null) {
      setOriginalVersion(prompt.version);
    }

    // 获取所有相关版本信息
    if (id && prompt?.title) {
      fetch(`/api/prompts?title=${encodeURIComponent(prompt.title)}`)
        .then((response) => response.json())
        .then((data) => {
          if (Array.isArray(data)) {
            setAllVersions(data.map(p => ({ id: p.id, version: p.version })));
          }
        })
        .catch((error) => console.error('Error fetching versions:', error));
    }

    fetch('/api/tags')
      .then((response) => response.json())
      .then((data) => {
        setTagOptions(data.map(tag => ({ value: tag.name, label: tag.name })));
      })
      .catch((error) => console.error('Error fetching tags:', error));
  }, [id, prompt, prompt?.title, originalVersion]);

  // 获取渠道信息
  useEffect(() => {
    const fetchChannels = async () => {
      if (!session?.user?.accessToken) return;
      
      try {
        const response = await fetch(`/api/models/channels`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setChannels(data.data);
        }
      } catch (error) {
        console.error('Error fetching channels:', error);
      }
    };

    fetchChannels();
  }, [session?.user?.accessToken]);

  // 当渠道改变时，获取对应的模型列表
  useEffect(() => {
    const fetchModels = async () => {
      if (!modelConfig.channel_id || !session?.user?.accessToken) {
        setModels([]);
        return;
      }

      try {
        const response = await fetch(`/api/models/models/${modelConfig.channel_id}`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setModels(data.data);
        }
      } catch (error) {
        console.error('Error fetching models:', error);
      }
    };

    fetchModels();
  }, [modelConfig.channel_id, session?.user?.accessToken]);

  if (!t) return <div className="flex justify-center items-center min-h-[70vh]"><Spinner className="w-8 h-8" /></div>;
  const tp = t.promptEditPage;
  if (!tp) return <div className="flex justify-center items-center min-h-[70vh]"><Spinner className="w-8 h-8" /></div>;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      // 渠道和模型验证
      if (!modelConfig.channel || modelConfig.channel.trim() === '') {
        toast({
          title: "错误",
          description: "渠道名称不能为空",
          variant: "destructive",
        });
        setIsSubmitting(false);
        return;
      }
      if (!modelConfig.model || modelConfig.model.trim() === '') {
        toast({
          title: "错误",
          description: "模型名称不能为空",
          variant: "destructive",
        });
        setIsSubmitting(false);
        return;
      }

      // 版本号验证
      const currentVersion = prompt.version;
      const originalVersionStr = originalVersion;


// 版本号比较函数已存在
const maxVersion = allVersions.reduce((max, v) => {
  if (compareVersions(v.version, max) > 0) return v.version;
  return max;
}, originalVersionStr);

// 只能填写当前版本号，或大于所有已有版本的最大版本号
if (
  currentVersion !== originalVersionStr &&
  compareVersions(currentVersion, maxVersion) <= 0
) {
  toast({
    title: "错误",
    description: `版本号只能等于当前版本，或大于现有最大版本（${maxVersion}）`,
    variant: "destructive",
  });
  setIsSubmitting(false);
  return;
}

      // 检查版本号是否与现有版本重复（排除当前id）
      if (
        allVersions.some(
          v => v.version === currentVersion && v.id !== prompt.id
        )
      ) {
        toast({
          title: "错误",
          description: "版本号不能与现有数据版本一致",
          variant: "destructive",
        });
        setIsSubmitting(false);
        return;
      }

      const isNewVersion = originalVersionStr !== currentVersion;
      const endpoint = `/api/prompts/updatePromptsById`;
      const method = 'POST';

      const modelPayload = {
        ...modelConfig,
        id: isNewVersion ? undefined : (modelConfig.id || undefined), // 新版本时不传ID，强制新增模型
        temperature: Number(modelConfig.temperature),
        max_tokens: Number(modelConfig.max_tokens),
        top_p: Number(modelConfig.top_p),
        presence_penalty: Number(modelConfig.presence_penalty),
        frequency_penalty: Number(modelConfig.frequency_penalty),
        n: Number(modelConfig.n),
        stop: modelConfig.stop ? modelConfig.stop.split(',').map(s => s.trim()).filter(Boolean) : null,
        logit_bias: modelConfig.logit_bias ? JSON.parse(modelConfig.logit_bias) : null,
        stream: Boolean(modelConfig.stream),
      };

      const submitData = {
        prompt: { 
          ...prompt,
          id: id  // 将id放入prompt对象中，而不是URL路径中
        },
        model: modelPayload
      };
      if (isNewVersion) {
        delete submitData.prompt.created_at;
        delete submitData.prompt.updated_at;
      }

      const response = await fetch(endpoint, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submitData),
      });

      if (response.ok) {
        const data = await response.json();
        toast({
          title: "成功",
          description: isNewVersion ? "新版本创建成功" : "更新成功",
        });
        router.push(`/prompts/${isNewVersion ? data.id : id}`);
      } else {
        const errorData = await response.json();
        toast({
          title: "错误",
          description: errorData.error || "操作失败",
          variant: "destructive",
        });
      }
    } catch (error) {
      toast({
        title: "错误",
        description: "操作失败，请重试",
        variant: "destructive",
      });
      console.error('Error updating prompt:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

      // 版本号比较函数
      const compareVersions = (v1, v2) => {
        const parts1 = v1.split('.').map(Number);
        const parts2 = v2.split('.').map(Number);

        for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
          const part1 = parts1[i] || 0;
          const part2 = parts2[i] || 0;

          if (part1 > part2) return 1;
          if (part1 < part2) return -1;
        }
        return 0;
      };
  const handleOptimize = async () => {
    if (!prompt.content.trim()) return;
    setIsOptimizing(true);
    setOptimizedContent('');
    setShowOptimizeModal(true);

    try {
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: prompt.content }),
      });

      if (!response.ok) throw new Error(tp.optimizeError);

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let tempContent = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());

        for (const line of lines) {
          try {
            const jsonStr = line.replace(/^data: /, '').trim();
            if (!jsonStr || jsonStr === '[DONE]') continue;

            const data = JSON.parse(jsonStr);
            if (data.choices?.[0]?.delta?.content) {
              tempContent += data.choices[0].delta.content;
              setOptimizedContent(tempContent);
            }
          } catch (e) {
            console.error(tp.optimizeParsingError, e);
          }
        }
      }

    } catch (error) {
      console.error(tp.optimizeErrorLog, error);
      toast({
        title: "错误",
        description: tp.optimizeRetry,
        variant: "destructive",
      });
    } finally {
      setIsOptimizing(false);
    }
  };

  const handleApplyOptimized = () => {
    setPrompt(prev => ({
      ...prev,
      content: optimizedContent
    }));
    setShowOptimizeModal(false);
    toast({
      title: "成功",
      description: tp.applyOptimizeSuccess,
    });
  };

  if (!prompt) {
    return (
      <div className="flex justify-center items-center min-h-[70vh]">
        <Spinner className="w-8 h-8" />
      </div>
    );
  }

  return (
    <>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="container max-w-3xl mx-auto p-6"
      >
        <div className="flex items-center gap-4 mb-8">
          <button
            onClick={() => router.back()}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
          </button>
          <h1 className="text-3xl font-bold">{tp.title}</h1>
        </div>

        <Card className="shadow-lg">
          <CardContent className="p-6">
            <form onSubmit={handleSubmit} className="space-y-8">
              <motion.div
                className="space-y-6"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.2 }}
              >
                <div className="space-y-2">
                  <Label htmlFor="title" className="text-lg font-medium">{tp.formTitleLabel}</Label>
                  <Input
                    id="title"
                    value={prompt.title}
                    onChange={(e) => setPrompt({ ...prompt, title: e.target.value })}
                    className="h-12"
                    placeholder={tp.formTitlePlaceholder}
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="content" className="text-lg font-medium">{tp.formContentLabel}</Label>
                  <div className="relative">
                    <Textarea
                      id="content"
                      value={prompt.content}
                      onChange={(e) => setPrompt({ ...prompt, content: e.target.value })}
                      className="min-h-[250px] resize-y pr-12"
                      placeholder={tp.formContentPlaceholder}
                      required
                    />
                    <Button
                      type="button"
                      size="icon"
                      variant="ghost"
                      className="absolute right-2 top-2 hover:bg-primary/10"
                      onClick={handleOptimize}
                      disabled={isOptimizing || !prompt.content.trim()}
                    >
                      {isOptimizing ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Wand2 className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description" className="text-lg font-medium">{tp.formDescriptionLabel}</Label>
                  <Textarea
                    id="description"
                    value={prompt.description}
                    onChange={(e) => setPrompt({ ...prompt, description: e.target.value })}
                    className="min-h-[80px] resize-y"
                    placeholder={tp.formDescriptionPlaceholder}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="tags" className="text-lg font-medium">{tp.formTagsLabel}</Label>
                  <CreatableSelect
                    id="tags"
                    isMulti
                    value={prompt.tags?.split(',').map(tag => ({ value: tag, label: tag })) || []}
                    onChange={(selected) => {
                      const tags = selected ? selected.map(option => option.value).join(',') : '';
                      setPrompt({ ...prompt, tags });
                    }}
                    options={tagOptions}
                    className="basic-multi-select"
                    classNamePrefix="select"
                    placeholder={tp.formTagsPlaceholder}
                    styles={{
                      control: (base) => ({
                        ...base,
                        minHeight: '2.5rem',
                      })
                    }}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        e.stopPropagation();
                      }
                    }}
                    onCreateOption={async (inputValue) => {
                      try {
                        const response = await fetch('/api/tags', {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                          },
                          body: JSON.stringify({ name: inputValue }),
                        });

                        if (response.ok) {
                          const newOption = { value: inputValue, label: inputValue };
                          setTagOptions([...tagOptions, newOption]);

                          const newTags = prompt.tags ? `${prompt.tags},${inputValue}` : inputValue;
                          setPrompt({ ...prompt, tags: newTags });
                        }
                      } catch (error) {
                        console.error('Error creating new tag:', error);
                      }
                    }}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="version" className="text-lg font-medium">{tp.formVersionLabel}</Label>
                  <Input
                    id="version"
                    value={prompt.version}
                    onChange={(e) => setPrompt({ ...prompt, version: e.target.value })}
                    className="h-12"
                    placeholder={tp.formVersionPlaceholder}
                  />
<div className="text-sm text-gray-600 space-y-1">
  <p>当前版本: {originalVersion}</p>
  <p>版本规则: 只能填写当前版本号，或大于现有最大版本</p>
  {allVersions.length > 0 && (
    <p>
      现有版本: {allVersions.map(v => v.version).join(', ')}，最大版本: {
        allVersions.reduce((max, v) => compareVersions(v.version, max) > 0 ? v.version : max, originalVersion)
      }
    </p>
  )}
</div>
                </div>
              </motion.div>

              <div className="space-y-2">
                <div 
                  className="flex items-center justify-between cursor-pointer select-none"
                  onClick={() => setShowModelConfig(!showModelConfig)}
                >
                  <Label className="text-lg font-medium">模型配置<span className="text-red-500 ml-1">*</span></Label>
                  <span className="text-sm text-muted-foreground">{showModelConfig ? '折叠' : '展开'}</span>
                </div>
                {showModelConfig && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border rounded-md p-4">
                  <div>
                    <Label>
                      渠道名称
                      <span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>渠道名称</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                      value={modelConfig.channel}
                      onChange={e => {
                        const selectedChannel = channels.find(ch => ch.name === e.target.value);
                        setModelConfig({ 
                          ...modelConfig, 
                          channel: e.target.value,
                          channel_id: selectedChannel ? selectedChannel.id : null,
                          model: '' // 清空模型选择
                        });
                      }}
                      required
                    >
                      <option value="">选择渠道</option>
                      {channels.map(channel => (
                        <option key={channel.id} value={channel.name}>
                          {channel.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <Label>
                      模型名称<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>选择渠道后获取可用模型列表</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className={`block w-full rounded-md border border-input bg-background px-3 py-2 text-sm ${!modelConfig.channel_id ? 'opacity-50 cursor-not-allowed' : ''}`}
                      value={modelConfig.model}
                      onChange={e => setModelConfig({ ...modelConfig, model: e.target.value })}
                      disabled={!modelConfig.channel_id}
                      required
                    >
                      <option value="">{modelConfig.channel_id ? '选择模型' : '请先选择渠道'}</option>
                      {models.map(model => (
                        <option key={model.model} value={model.model}>
                          {model.model}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <Label>
                      temperature<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>控制输出随机性：值越高越随机，值越低越确定，取值范围 [0, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" step="0.1" min={0} max={2} value={modelConfig.temperature} onChange={e => setModelConfig({ ...modelConfig, temperature: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      max_tokens<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>生成内容的最大 token 数量（[10, 30000]，默认 2048）</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" min={10} max={30000} value={modelConfig.max_tokens} onChange={e => setModelConfig({ ...modelConfig, max_tokens: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      top_p<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>核采样，仅考虑累积概率达到阈值的 token，取值范围 [0, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" step="0.1" min={0} max={2} value={modelConfig.top_p} onChange={e => setModelConfig({ ...modelConfig, top_p: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      presence_penalty<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>鼓励新话题：正值增加新主题概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" step="0.1" min={-2} max={2} value={modelConfig.presence_penalty} onChange={e => setModelConfig({ ...modelConfig, presence_penalty: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      frequency_penalty<span className="text-red-500 ml-1">*</span>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>惩罚重复：正值降低重复内容概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" step="0.1" min={-2} max={2} value={modelConfig.frequency_penalty} onChange={e => setModelConfig({ ...modelConfig, frequency_penalty: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      n
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>生成多个独立回复（如 n=3 返回 3 个选项），用于结果多样性选择</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input type="number" value={modelConfig.n} onChange={e => setModelConfig({ ...modelConfig, n: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      stop (逗号分隔)
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>设置停止词，遇到即终止生成（如 ["\n", "。"]）</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input value={modelConfig.stop} onChange={e => setModelConfig({ ...modelConfig, stop: e.target.value })} />
                  </div>
                  <div>
                    <Label>
                      logit_bias (JSON)
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>{'调整特定 token 的生成概率（如 {"1234": 2.0}）'}</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input value={modelConfig.logit_bias} onChange={e => setModelConfig({ ...modelConfig, logit_bias: e.target.value })} placeholder='{"123": -5}' />
                  </div>
                  <div>
                    <Label>
                      stream
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>启用流式传输，逐块返回结果</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <select
                      className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                      value={modelConfig.stream ? 'true' : 'false'}
                      onChange={e => setModelConfig({ ...modelConfig, stream: e.target.value === 'true' })}
                    >
                      <option value="false">false</option>
                      <option value="true">true</option>
                    </select>
                  </div>
                  <div>
                    <Label>
                      api_key
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>调用第三方服务的密钥</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </Label>
                    <Input value={modelConfig.api_key} onChange={e => setModelConfig({ ...modelConfig, api_key: e.target.value })} />
                  </div>
                </div>
                )}
              </div>

              <div className="flex gap-4 pt-4">
                <Button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-32 h-12"
                >
                  {isSubmitting ? (
                    <div className="flex items-center gap-2">
                      <Spinner className="w-4 h-4" />
                      <span>{tp.saving}</span>
                    </div>
                  ) : tp.save}
                </Button>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => router.back()}
                  className="w-32 h-12"
                >
                  {tp.cancel}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </motion.div>

      <Modal isOpen={showOptimizeModal} onClose={() => setShowOptimizeModal(false)}>
        <ModalContent className="max-w-3xl max-h-[80vh]">
          <ModalHeader>
            <ModalTitle>{tp.optimizePreviewTitle}</ModalTitle>
          </ModalHeader>
          <div className="relative min-h-[200px] max-h-[50vh] overflow-y-auto">
            <Textarea
              value={optimizedContent}
              onChange={(e) => setOptimizedContent(e.target.value)}
              className="min-h-[200px] w-full"
              placeholder={tp.optimizePlaceholder}
            />
          </div>
          <ModalFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setShowOptimizeModal(false)}
              className="mr-2"
            >
              {tp.cancel}
            </Button>
            <Button
              type="button"
              onClick={handleApplyOptimized}
              disabled={!optimizedContent.trim()}
            >
              {tp.applyOptimization}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
} 